package ui.strategy;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import tool.LongStringTransformer;
import tool.MyButton;
import tool.MyLabel;
import vo.CommodityVo;
import vo.CouponsVo;
import vo.UserVo;
import vo.Vo;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;

import blservice.strategy.StrategyBLService;
import client.boot.BLServiceManager;

import java.awt.Font;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.awt.Color;

public class CouponsPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	List<CouponsVo> vo;
	UserVo user;
	private JTable table;
	private JScrollPane jsp;
	
	private JTextField total_require;
	@SuppressWarnings("unused")
	private boolean isNew;
	private boolean editable;
	private tool.DateChooserJButton tfFromDate;
	private tool.DateChooserJButton tfToDate;
	private JComboBox<String> client;
	@SuppressWarnings("unused")
	private List<CommodityVo> commodities;

	/**
	 * 
	 * @param user
	 * @param vo
	 *            如果是单据查询，则传入vo，如果是单据制定则传入null;
	 * @param editable
	 *            如果是新建或者红冲并复制就设置成editable
	 * @param 红冲 
	 */
	public CouponsPanel(UserVo user, CouponsVo vo, boolean editable) {
		this.user = user;
		this.setLayout(null);
		this.setOpaque(false);
		this.editable = editable;
		this.vo = new ArrayList<CouponsVo>();
		if (vo == null) {
			isNew = true;
		} else {
			isNew = false;
			this.vo.add(vo);
		}
		
		JLabel lblNewLabel = new JLabel("制定代金券");
		lblNewLabel.setForeground(Color.WHITE);
		lblNewLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		lblNewLabel.setBounds(265, 0, 100, 20);
		add(lblNewLabel);
		
		

		JLabel lblFromDate = new MyLabel("起始时间");
		lblFromDate.setBounds(47, 30, 65, 15);
		add(lblFromDate);

		tfFromDate = new tool.DateChooserJButton();
		tfFromDate.setBounds(104, 28, 78, 19);
		add(tfFromDate);

		JLabel lblToDate = new MyLabel("\u7ED3\u675F\u65F6\u95F4");
		lblToDate.setBounds(200, 30, 70, 15);
		add(lblToDate);

		tfToDate = new tool.DateChooserJButton();
		tfToDate.setBounds(272, 28, 78, 19);
		add(tfToDate);
		
		JLabel label_2 = new MyLabel("客户级别：");
		label_2.setBounds(399, 30, 100, 15);
		add(label_2);
		
		client = new JComboBox<String>();
		client.setModel(new DefaultComboBoxModel<String>(new String[] { "一级",
				"二级", "三级", "四级", "五级" }));

		client.setBounds(471, 25, 78, 24);
		add(client);
		
		
		
		JLabel label_4 = new MyLabel("总额要求：");
		label_4.setBounds(47, 77, 80, 15);
		add(label_4);
		
		total_require = new JTextField();
		total_require.setColumns(10);
		total_require.setBounds(145, 74, 105, 21);
		add(total_require);
		

		

		JButton add = new MyButton("Graphics/Button45-23.png");
		add.setText("+");
		add.setBounds(465,96, 45, 23);
		if (!editable) {
			add.setVisible(false);
		}
		add.addActionListener(e -> addLine());
		add(add);

		

		JButton submit = new MyButton("Graphics/Button93-23.png");
		submit.setText("\u63D0\u4EA4");
		submit.setBounds(489, 393, 93, 23);
		submit.addActionListener(e -> submit());
		if (!editable) {
			submit.setVisible(false);
		}
		
		add(submit);

		JButton sub = new JButton("-");
		sub.setBounds(537, 96, 45, 23);
		sub.addActionListener(e -> subLine());
		if (!editable) {
			sub.setVisible(false);
		}
		add(sub);

		table = new JTable() {
			private static final long serialVersionUID = 3028897666676861555L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return editable;
			}
		};
		table.setBounds(47, 128, 535, 248);
		jsp = new JScrollPane(table);
		jsp.setBounds(47, 128, 535, 248);
		jsp.setVisible(true);
		this.add(jsp);
		
		displayTable();
	}

	void displayTable() {
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "面值", "赠送数量" });

		for (CouponsVo o : vo) {
			model.addRow(new String[] {
					LongStringTransformer.LongToString(o.getValue()),
					Integer.toString(o.getNum()) });
		}
		if (editable) {
			model.addRow(new String[] { "", "" });
		}
		table.setModel(model);
		
	}

	void saveTable() {
		List<CouponsVo> items = vo;
		items.clear();
		for (int i = 0; i < table.getRowCount(); i++) {
			CouponsVo temp = new CouponsVo();
			if(((String) table.getValueAt(i, 0)).equals("")){
				continue;
			}
			try{
		   temp.setValue(LongStringTransformer.StringToLong((String) table.getValueAt(i, 0)));
			}catch (NumberFormatException e) {
				JOptionPane.showMessageDialog(this, "面值格式错误\n" + e.getMessage());
				e.printStackTrace();
				return;
			}
			boolean successed = false;
			try {
				int num = Integer.parseInt((String) table
						.getValueAt(i, 1));
				temp.setNum(num);
				successed = true;
			} catch (NumberFormatException e) {
				JOptionPane.showMessageDialog(this, "数量格式错误\n" + e.getMessage());
				e.printStackTrace();
				return;
			}
			if (successed) {
				items.add(temp);
			}
		}
	}

	void subLine() {
		int line = table.getSelectedRow();
		if (line == -1 || line >= vo.size()) {
			return;
		} else {
			vo.remove(line);
			displayTable();
		}
	}

	void addLine() {
		saveTable();
		displayTable();
	}

	void submit() {
		saveTable();
		displayTable();
		if (vo.size() == 0) {
			JOptionPane.showMessageDialog(this, "请填写代金券信息\n");
			return;
		}
		if(new SimpleDateFormat("yyyy-mm-dd").format(tfFromDate.getDate()).compareTo(new SimpleDateFormat("yyyy-mm-dd").format(tfToDate.getDate()))>0){
			JOptionPane.showMessageDialog(this, "起始日期大于结束日期！\n");
			return;
		}
		StrategyBLService bl;
		try {
			bl = BLServiceManager.getStrategyBLService(null);
			ArrayList<Integer> removing=new ArrayList<Integer>();
			for (int i = 0; i < vo.size(); i++) {
				vo.get(i).setOperator(user.getName());
				vo.get(i).setOperation("制定代金券策略");
	            vo.get(i).setFrom(tfFromDate.getDate());	
	            vo.get(i).setTo(tfToDate.getDate());
	            vo.get(i).set客户级别(client.getSelectedIndex());
	            try {
	            	 vo.get(i).set总额条件(LongStringTransformer.StringToLong(total_require.getText()));
				} catch (NumberFormatException e) {
					JOptionPane.showMessageDialog(this, "总额要求格式错误\n" + e.getMessage());
					e.printStackTrace();
					return;
				}
	           
	           
				Vo result;
		        result = bl.saveCoupons(vo.get(i));
				if (result.isSuccessed()) {
					JOptionPane.showMessageDialog(this, "代金券制定成功\n");
					if(i<vo.size()&&i>=0)
						removing.add(i);

				} else {
					JOptionPane.showMessageDialog(this,
							"代金券制定失败\n" + result.getFailMessage());
				}
			}
			removing.sort(new Comparator<Integer>() {
				@Override
				public int compare(Integer o1, Integer o2) {
					return o1-o2;
				}
				
			});
			for(int i=removing.size()-1;i>=0;i--){
				vo.remove((int)removing.get(i));
			}
		} catch (RemoteException | MalformedURLException | SQLException
				| NotBoundException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
		displayTable();
	}

	
	
	
}